#include "backforward.h"

BackForward::BackForward(TabManager* tabManager) : tabManager(tabManager)
{

}
void BackForward::on_back()
{
    tabManager->text1->blockSignals(true);
    //防止在撤销时也触发文本变化的函数，先将文本变化的信号阻隔
    if(tabManager->back_text[tabManager->tab_index].size()>1)
        for(int i=1;i<tabManager->back_text[tabManager->tab_index].size();i++)
        {
            if(tabManager->back_text[tabManager->tab_index][i] == tabManager->text1->toPlainText())
            {   tabManager->text1->setPlainText(tabManager->back_text[tabManager->tab_index][i-1]);
                back_index = i;
                break;
            }
        }
    //进行文本撤销操作，即将历史文本列表中上一步的文本赋值给当前文本
    tabManager->mainWindow->forward->setEnabled(true);
    if(back_index == 1)
        tabManager->mainWindow->back->setEnabled(false);
    tabManager->text1->blockSignals(false);
    //取消对文本变化信号的阻隔
}
void BackForward::on_forward()
{
    tabManager->text1->blockSignals(true);
    if (back_index < tabManager->back_text[tabManager->tab_index].size())
    {
        tabManager->text1->setPlainText(tabManager->back_text[tabManager->tab_index][back_index]);
        back_index += 1;
    }
    //执行文本“前进”操作，即取消撤销操作
    if (back_index >= tabManager->back_text[tabManager->tab_index].size())
    {
        tabManager->mainWindow->forward->setEnabled(false);
    }
    tabManager->mainWindow->back->setEnabled(true);
    tabManager->text1->blockSignals(false);
}
void BackForward::on_text_changed_back()
{
    tabManager->text1->blockSignals(true);
    //暂时阻隔文本变化的信号
    QList<QString> temp_list;
    //临时列表。在用户使用“撤销”功能后对文本进行修改时，要将之前存在过的“未来”的文本舍弃，将此时刻之前的历史文本赋值给临时列表，再给历史文本重新赋值，如下
    bool found = false;
    for (int i = 0; i < tabManager->back_text[tabManager->tab_index].size(); ++i)
    {
        if (tabManager->back_text[tabManager->tab_index][i] == tabManager->text1->toPlainText())
        {
            found = true;
            break;
        }
        temp_list.append(tabManager->back_text[tabManager->tab_index][i]);
    }
    if (found)
    {
        tabManager->back_text[tabManager->tab_index] = temp_list;
    }
    tabManager->back_text[tabManager->tab_index].append(tabManager->text1->toPlainText());
    //back_text是以历史文本列表为元素的列表，tab_index表示操作的是当前标签页的历史文本列表，在文本变化时将文本储存到这个列表中
    if (tabManager->back_text[tabManager->tab_index].size() > 50)
    //防止占用内存过大，撤销操作只支持50步以内
    {
        tabManager->back_text[tabManager->tab_index].removeFirst();
    }
    tabManager->mainWindow->forward->setEnabled(false);
    tabManager->mainWindow->back->setEnabled(true);

    tabManager->text1->blockSignals(false);
}
